﻿using Newtonsoft.Json;

namespace Devonline.Core;

public class DecimalConverter(string format) : JsonConverter
{
    private readonly string _format = format;

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(decimal) || objectType == typeof(double) || objectType == typeof(float);
    }

    public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
    {
        return reader.ReadAsDecimal();
    }

    public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
    {
        if (value is not null && (value is decimal || value is double || value is float))
        {
            writer.WriteValue(string.Format(_format, value));
        }
        else
        {
            writer.WriteValue(string.Empty);
        }
    }
}